import type {
  Novel,
  Chapter,
  Comment,
  RecommendationItem,
  NovelCategory,
  NovelStatus,
} from "@/types";
import { apiClient } from "./index";

// 后端API响应类型定义
interface ApiResponse<T = unknown> {
  success: boolean;
  data?: T;
  message: string;
}

// 后端数据类型定义
interface BackendNovel {
  id: number;
  title: string;
  author: string;
  author_id: number;
  description: string;
  cover_url: string;
  category: string;
  tags: string[];
  status: string;
  word_count: number;
  chapter_count: number;
  rating: string;
  rating_count: number;
  view_count: number;
  favorite_count: number;
  is_vip: number;
  price: number;
  created_at: string;
  updated_at: string;
  last_chapter_title?: string;
  last_chapter_time?: string;
}

interface BackendChapter {
  id: number;
  title: string;
  chapter_number: number;
  content?: string;
  word_count: number;
  is_vip: number;
  price: number;
  created_at: string;
  updated_at: string;
}

interface NovelResponse {
  novel: BackendNovel;
  chapters?: BackendChapter[];
  isInBookshelf?: boolean;
  readingProgress?: number;
}

/**
 * 根据分类获取小说列表
 */
export const getNovelsByCategory = async (category?: string): Promise<Novel[]> => {
  const params = new URLSearchParams();
  if (category) {
    params.set("category", category);
  }

  const response = await apiClient.get(`/novels?${params.toString()}`);

  // 后端返回的数据结构是 { success: true, data: [...], total: number }
  if (!response.success || !response.data) {
    throw new Error(response.message || "获取小说列表失败");
  }

  // 转换后端数据格式到前端格式
  return (response.data as BackendNovel[]).map((novel: BackendNovel) => ({
    id: novel.id.toString(),
    title: novel.title,
    author: novel.author || "Unknown Author",
    authorId: novel.author_id?.toString() || "0",
    cover: novel.cover_url || "https://via.placeholder.com/300x400",
    description: novel.description || "",
    category: novel.category as NovelCategory,
    status: novel.status === "completed" ? "completed" : "ongoing",
    wordCount: novel.word_count || 0,
    chapterCount: novel.chapter_count || 0,
    rating: parseFloat(novel.rating) || 0,
    ratingCount: novel.rating_count || 0,
    viewCount: novel.view_count || 0,
    favoriteCount: novel.favorite_count || 0,
    tags: Array.isArray(novel.tags) ? novel.tags : [],
    isVip: Boolean(novel.is_vip),
    price: novel.price || 0,
    createdAt: novel.created_at,
    updatedAt: novel.updated_at,
    lastChapterTitle: novel.last_chapter_title || "",
    lastChapterTime: novel.last_chapter_time || novel.updated_at,
  }));
};

/**
 * 根据ID获取小说详情
 */
export const getNovelById = async (id: string): Promise<Novel | undefined> => {
  try {
    const response = await apiClient.get(`/novels/${id}`);

    if (!response.success || !response.data) {
      return undefined;
    }

    const novel = response.data as BackendNovel;

    return {
      id: novel.id.toString(),
      title: novel.title,
      author: novel.author || "Unknown Author",
      authorId: novel.author_id?.toString() || "0",
      cover: novel.cover_url || "https://via.placeholder.com/300x400",
      description: novel.description || "",
      category: novel.category,
      status: novel.status === "completed" ? "completed" : "ongoing",
      wordCount: novel.word_count || 0,
      chapterCount: novel.chapter_count || 0,
      rating: parseFloat(novel.rating) || 0,
      ratingCount: novel.rating_count || 0,
      viewCount: novel.view_count || 0,
      favoriteCount: novel.favorite_count || 0,
      tags: Array.isArray(novel.tags) ? novel.tags : [],
      isVip: Boolean(novel.is_vip),
      price: novel.price || 0,
      createdAt: novel.created_at,
      updatedAt: novel.updated_at,
      lastChapterTitle: novel.last_chapter_title || "",
      lastChapterTime: novel.last_chapter_time || novel.updated_at,
    };
  } catch (error) {
    console.error("Error fetching novel:", error);
    return undefined;
  }
};

/**
 * 获取小说章节列表
 */
export const getChaptersByNovelId = async (novelId: string): Promise<Chapter[]> => {
  try {
    const response = await apiClient.get(`/novels/${novelId}/chapters`);

    return response.data.map((chapter: any) => ({
      id: chapter.id.toString(),
      novelId: chapter.novel_id.toString(),
      chapterNumber: chapter.chapter_number,
      title: chapter.title,
      content: chapter.content || "",
      wordCount: chapter.word_count || 0,
      isVip: Boolean(chapter.is_vip),
      price: chapter.price || 0,
      isFree: !chapter.is_vip || chapter.price === 0,
      createdAt: chapter.created_at,
      updatedAt: chapter.updated_at,
    }));
  } catch (error) {
    console.error("Error fetching chapters:", error);
    return [];
  }
};

/**
 * 获取章节内容
 */
export const getChapterById = async (id: string): Promise<Chapter | undefined> => {
  try {
    // 这里需要创建一个单独的章节详情API
    // 暂时通过小说章节列表来获取
    const response = await apiClient.get(`/chapters/${id}`);
    const chapter = response.data;

    if (!chapter) return undefined;

    return {
      id: chapter.id.toString(),
      novelId: chapter.novel_id.toString(),
      chapterNumber: chapter.chapter_number,
      title: chapter.title,
      content: chapter.content || "",
      wordCount: chapter.word_count || 0,
      isVip: Boolean(chapter.is_vip),
      price: chapter.price || 0,
      isFree: !chapter.is_vip || chapter.price === 0,
      createdAt: chapter.created_at,
      updatedAt: chapter.updated_at,
    };
  } catch (error) {
    console.error("Error fetching chapter:", error);
    return undefined;
  }
};

/**
 * 获取小说评论
 */
export const getCommentsByNovelId = async (novelId: string): Promise<Comment[]> => {
  try {
    const response = await apiClient.get(`/novels/${novelId}/comments`);

    return response.data.map((comment: any) => ({
      id: comment.id.toString(),
      novelId: comment.novel_id.toString(),
      userId: comment.user_id.toString(),
      userName: comment.user_name || "Anonymous",
      userAvatar: comment.user_avatar || "https://via.placeholder.com/40",
      content: comment.content,
      rating: comment.rating || 0,
      likeCount: comment.like_count || 0,
      replyCount: comment.reply_count || 0,
      createdAt: comment.created_at,
    }));
  } catch (error) {
    console.error("Error fetching comments:", error);
    return [];
  }
};

/**
 * 获取推荐小说
 */
export const getRecommendations = async (userId?: string): Promise<RecommendationItem[]> => {
  try {
    const params = new URLSearchParams();
    if (userId) {
      params.set("userId", userId);
    }

    const response = await apiClient.get(`/novels/recommendations?${params.toString()}`);

    return response.data.map((item: any) => ({
      novel: {
        id: item.novel.id.toString(),
        title: item.novel.title,
        author: item.novel.author || "Unknown Author",
        authorId: item.novel.author_id?.toString() || "0",
        cover: item.novel.cover_url || "https://via.placeholder.com/300x400",
        description: item.novel.description || "",
        category: item.novel.category,
        status: item.novel.status === "completed" ? "completed" : "ongoing",
        wordCount: item.novel.word_count || 0,
        chapterCount: item.novel.chapter_count || 0,
        rating: item.novel.rating || 0,
        ratingCount: item.novel.rating_count || 0,
        viewCount: item.novel.view_count || 0,
        favoriteCount: item.novel.favorite_count || 0,
        tags: Array.isArray(item.novel.tags)
          ? item.novel.tags
          : item.novel.tags
            ? JSON.parse(item.novel.tags)
            : [],
        isVip: Boolean(item.novel.is_vip),
        price: item.novel.price_per_chapter || 0,
        createdAt: item.novel.created_at,
        updatedAt: item.novel.updated_at,
        lastChapterTitle: "",
        lastChapterTime: item.novel.updated_at,
      },
      score: item.score || 0.5,
      reason: item.reason || "为您推荐",
      type: item.type || "popular",
    }));
  } catch (error) {
    console.error("Error fetching recommendations:", error);
    // 如果推荐API不存在，返回空数组
    return [];
  }
};

/**
 * 搜索小说
 */
export const searchNovels = async (keyword: string): Promise<Novel[]> => {
  try {
    const params = new URLSearchParams();
    params.set("search", keyword);

    const response = await apiClient.get(`/novels?${params.toString()}`);

    return response.data.map((novel: any) => ({
      id: novel.id.toString(),
      title: novel.title,
      author: novel.author || "Unknown Author",
      authorId: novel.author_id?.toString() || "0",
      cover: novel.cover_url || "https://via.placeholder.com/300x400",
      description: novel.description || "",
      category: novel.category,
      status: novel.status === "completed" ? "completed" : "ongoing",
      wordCount: novel.word_count || 0,
      chapterCount: novel.chapter_count || 0,
      rating: novel.rating || 0,
      ratingCount: novel.rating_count || 0,
      viewCount: novel.view_count || 0,
      favoriteCount: novel.favorite_count || 0,
      tags: Array.isArray(novel.tags) ? novel.tags : novel.tags ? JSON.parse(novel.tags) : [],
      isVip: Boolean(novel.is_vip),
      price: novel.price_per_chapter || 0,
      createdAt: novel.created_at,
      updatedAt: novel.updated_at,
      lastChapterTitle: "",
      lastChapterTime: novel.updated_at,
    }));
  } catch (error) {
    console.error("Error searching novels:", error);
    return [];
  }
};

/**
 * 获取热门小说
 */
export const getPopularNovels = async (): Promise<Novel[]> => {
  try {
    const response = await apiClient.get("/novels?sort=popular&limit=10");

    return response.data.map((novel: any) => ({
      id: novel.id.toString(),
      title: novel.title,
      author: novel.author || "Unknown Author",
      authorId: novel.author_id?.toString() || "0",
      cover: novel.cover_url || "https://via.placeholder.com/300x400",
      description: novel.description || "",
      category: novel.category,
      status: novel.status === "completed" ? "completed" : "ongoing",
      wordCount: novel.word_count || 0,
      chapterCount: novel.chapter_count || 0,
      rating: novel.rating || 0,
      ratingCount: novel.rating_count || 0,
      viewCount: novel.view_count || 0,
      favoriteCount: novel.favorite_count || 0,
      tags: Array.isArray(novel.tags) ? novel.tags : novel.tags ? JSON.parse(novel.tags) : [],
      isVip: Boolean(novel.is_vip),
      price: novel.price_per_chapter || 0,
      createdAt: novel.created_at,
      updatedAt: novel.updated_at,
      lastChapterTitle: "",
      lastChapterTime: novel.updated_at,
    }));
  } catch (error) {
    console.error("Error fetching popular novels:", error);
    return [];
  }
};

/**
 * 获取最新更新小说
 */
export const getLatestNovels = async (): Promise<Novel[]> => {
  try {
    const response = await apiClient.get("/novels?sort=latest&limit=10");

    return response.data.map((novel: any) => ({
      id: novel.id.toString(),
      title: novel.title,
      author: novel.author || "Unknown Author",
      authorId: novel.author_id?.toString() || "0",
      cover: novel.cover_url || "https://via.placeholder.com/300x400",
      description: novel.description || "",
      category: novel.category,
      status: novel.status === "completed" ? "completed" : "ongoing",
      wordCount: novel.word_count || 0,
      chapterCount: novel.chapter_count || 0,
      rating: novel.rating || 0,
      ratingCount: novel.rating_count || 0,
      viewCount: novel.view_count || 0,
      favoriteCount: novel.favorite_count || 0,
      tags: Array.isArray(novel.tags) ? novel.tags : novel.tags ? JSON.parse(novel.tags) : [],
      isVip: Boolean(novel.is_vip),
      price: novel.price_per_chapter || 0,
      createdAt: novel.created_at,
      updatedAt: novel.updated_at,
      lastChapterTitle: "",
      lastChapterTime: novel.updated_at,
    }));
  } catch (error) {
    console.error("Error fetching latest novels:", error);
    return [];
  }
};
